const server = require("../../utils/server");
const app = getApp();

// pages/dish/dish.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dishList: null,
    currentIndex: 0,
    selecteId: '',
    totalPrice: 0,
    totalNumber: 0,
    cartList: [],
    scrollHeight: [],
    
  },

  getDishList() {
    let that = this;
    server.requestForm(true, 'get', 'goodsType/tree?storeId=' + wx.getStorageSync('toStoreInfoPageId'), {}, function (res) {
      if (res.code == 0) {
        let list = res.data;
        list.forEach((item, index) => {
          item.goodsList.forEach((_item, _index) => {
            _item.salesNumber = 0
          })
        })
        that.setData({
          dishList: list
        });
        wx.nextTick(function () {
          let query = wx.createSelectorQuery().in(that);
          let newList = new Array();
          query.selectAll(".pro-name").boundingClientRect(function (res) {
            for (let index = 0; index < res.length; index++) {
              let list = {};
              let height = res[index].top - res[0].top;
              list.height = height;
              newList.push(list)
            };
            that.setData({
              scrollHeight: newList
            })
          }).exec();
        })
      } else {

      }
    });
  },

  scrollView(e) {
    let that = this;
    let heightlist = that.data.scrollHeight;
    let height = e.detail.scrollTop;
    let _index = 0;
    let flag = false;
    heightlist.forEach((item, index) => {
      if (height >= heightlist[index].height && height <= heightlist[index + 1].height) {
        flag = true;
        _index = index
      }
    });
    if (flag) {
      that.setData({
        currentIndex: _index
      })
    }
  },

  selectedType(e) {
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    this.setData({
      currentIndex: index,
      selecteId: id
    })
  },

  addNumber(e) {
    let that = this;
    let goods = e.currentTarget.dataset.item;
    let id = goods._id
    let dishList = that.data.dishList;
    let body = new Object;
    body.goodsId = id;
    body.mallId = wx.getStorageSync('currentMellId');
    body.storeId = wx.getStorageSync('toStoreInfoPageId');
    body.buyCount = 1;
    server.requestForm(true, 'post', 'cart', JSON.stringify(body), function (res) {
      if (res.code != 0) {
        wx.showToast({
          title: '加入购物车失败',
        })
      } else {
        let cartId = res.data;
        dishList.forEach((item, index) => {
          item.goodsList.forEach((_item, _index) => {
            if (_item._id == id) {
              _item.salesNumber++;
              _item.cartId = cartId
              goods = _item;
            }
          })
        });
        that.setData({
          dishList: dishList
        });
        console.log(goods)
        that.addcart(goods);
      }
    });

  },

  addcart(goods) {
    let cartList = this.data.cartList;
    let flag = true;
    if (cartList.length == 0) {
      cartList.push(goods)
    } else {
      cartList.forEach((item, index) => {
        if (item._id == goods._id) {
          item.salesNumber = goods.salesNumber
          flag = false
        }
      });
      if (flag) {
        cartList.push(goods)
      }
    }
    this.setData({
      cartList: cartList
    });
    this.checkCart();
  },

  lessNumber(e) {
    let that = this;
    let goods = e.currentTarget.dataset.item;
    let body = new Object;
    body.mallId = wx.getStorageSync('currentMellId')
    body.storeId = wx.getStorageSync('toStoreInfoPageId');
    body.goodsId = goods.cartId;
    body.buyCount = -1;
    server.requestForm(true, 'post', 'cart', JSON.stringify(body), function (res) {
      if (res.code != 0) {
        wx.showToast({
          title: '减少数量失败',
          icon: 'none'
        })
      } else {
        let dishList = that.data.dishList;
        dishList.forEach((item, index) => {
          item.goodsList.forEach((_item, _index) => {
            if (_item._id == goods._id) {
              _item.salesNumber - 1;
              console.log(_item)
            }
          })
        });
        that.setData({
          dishList: dishList
        });
        that.lessCart(goods);
      }
    })
  },

  lessCart(goods) {
    let number = goods.salesNumber - 1;
    let cartList = this.data.cartList;
    if (cartList.length == 0) {
      return false
    } else {
      cartList.forEach((item, index) => {
        if (item._id == goods._id) {
          item.salesNumber = number;
          if (item.salesNumber == 0) {
            cartList.splice(index, 1)
          }
        }
      })
    };
    this.setData({
      cartList: cartList
    });
    this.checkCart();
  },

  checkCart() {
    let cartList = this.data.cartList;
    let totalPrice = 0;
    let totalNumber = 0;
    if (cartList.length) {
      cartList.forEach((item, index) => {
        totalPrice += item.salePrice * item.salesNumber;
        totalNumber += item.salesNumber
      })
    };
    this.setData({
      totalPrice: totalPrice,
      totalNumber: totalNumber
    })
  },

  checkOrder() {
    let list = this.data.cartList;
    let newList = JSON.stringify(list);
    if (list.length == 0) {
      wx.showToast({
        title: '您还未选购商品',
        icon: "none",
        duration: 1000
      })
      return false
    };
    wx.setStorageSync('cartList', list)
    wx.navigateTo({
      url: '/pages/dish/pay/pay'
    })
  },

  goCart() {
    let list = this.data.cartList;
    if (list.length == 0) {
      wx.showToast({
        title: '您还未选购商品',
        icon: "none",
        duration: 1000
      })
      return false
    };
    wx.setStorageSync('cartList', list)
    wx.switchTab({
      url: '/pages/dish/cart/cart'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.getDishList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let tabbar = this.selectComponent("#tabbar");
    tabbar.setData({
      selected: 1
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})